package com.industrial.premu.service.impl;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.DictUtils;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.PreMuBenefitEvaluation;
import com.industrial.premu.domain.PreMuIndexWeight;
import com.industrial.premu.domain.PreMuIndexWeightSub;
import com.industrial.premu.domain.sqsj.PreMuImportAddSubstract;
import com.industrial.premu.domain.sqsj.PreMuImportCustomIndexLj;
import com.industrial.premu.dto.IndexWeightParamsDto;
import com.industrial.premu.dto.PreMuIndexWeightMainDto;
import com.industrial.premu.mapper.PreMuBenefitEvaluationMapper;
import com.industrial.premu.mapper.PreMuIndexWeightMapper;
import com.industrial.premu.mapper.PreMuIndexWeightSubMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportAddSubstractMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportCustomIndexLjMapper;
import com.industrial.premu.vo.PreMuIndexWeightMainVo;
import com.industrial.system.api.domain.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.bouncycastle.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.industrial.premu.mapper.PreMuIndexWeightMainMapper;
import com.industrial.premu.domain.PreMuIndexWeightMain;
import com.industrial.premu.service.IPreMuIndexWeightMainService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 指标管理主Service业务层处理
 *
 * @author SangGuangCan
 * @date 2024-01-23
 */
@Service
public class PreMuIndexWeightMainServiceImpl implements IPreMuIndexWeightMainService
{
    @Autowired
    private PreMuIndexWeightMainMapper preMuIndexWeightMainMapper;

    @Autowired
    private PreMuIndexWeightSubMapper preMuIndexWeightSubMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PreMuImportCustomIndexLjMapper preMuImportCustomIndexLjMapper;

    /**
     * 查询指标管理主
     *
     * @param baseId 指标管理主主键
     * @return 指标管理主
     */
    @Override
    public PreMuIndexWeightMain selectPreMuIndexWeightMainByBaseId(String baseId)
    {
        return preMuIndexWeightMainMapper.selectPreMuIndexWeightMainByBaseId(baseId);
    }

    /**
     * 查询指标管理主列表
     *
     * @param preMuIndexWeightMain 指标管理主
     * @return 指标管理主
     */
    @Override
    public List<PreMuIndexWeightMain> selectPreMuIndexWeightMainList(PreMuIndexWeightMain preMuIndexWeightMain)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        String district = sysUser.getDistrict();
        if(StringUtils.isBlank(district)){
            throw new RuntimeException("没有找到该用户的行政区代码");
        }
        preMuIndexWeightMain.setCounty(district);
        return preMuIndexWeightMainMapper.selectPreMuIndexWeightMainListNew(preMuIndexWeightMain);
    }

    /**
     * 新增指标管理主
     *
     * @param preMuIndexWeightMain 指标管理主
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertPreMuIndexWeightMain(PreMuIndexWeightMain preMuIndexWeightMain)
    {


        List<PreMuIndexWeightSub> preMuIndexWeightSubList = preMuIndexWeightMain.getPreMuIndexWeightSubList();
        if(preMuIndexWeightMainMapper == null || preMuIndexWeightSubList.isEmpty()){
            throw new RuntimeException("并没有找到设置的指标");
        }
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        String district = sysUser.getDistrict();
        PreMuIndexWeightMain params = new PreMuIndexWeightMain();
        params.setCounty(district);
        params.setYear(preMuIndexWeightMain.getYear());
        params.setCompanyType(preMuIndexWeightMain.getCompanyType());
        String industries = preMuIndexWeightMain.getIndustry();
        String parks = preMuIndexWeightMain.getPark();
        String[] industryArray = new String[]{};
        String[] parkArray = new String[]{};
        if(!StringUtils.isEmpty(industries)){
            industryArray = industries.split(",");

        }
        if(!StringUtils.isEmpty(parks)){
            parkArray = parks.split(",");

        }
        PreMuIndexWeightMainDto dto = new PreMuIndexWeightMainDto();
        dto.setCounty(district);
        dto.setYear(preMuIndexWeightMain.getYear());
        dto.setCompanyType(preMuIndexWeightMain.getCompanyType());
        if(!Arrays.isNullOrEmpty(industryArray) && !Arrays.isNullOrEmpty(parkArray)){
            dto.setWeightType("03");
        }else{
            if(!Arrays.isNullOrEmpty(industryArray) || !Arrays.isNullOrEmpty(parkArray)){
                if(Arrays.isNullOrEmpty(industryArray)){
                    dto.setWeightType("02");
                }else if(Arrays.isNullOrEmpty(parkArray)){
                    dto.setWeightType("01");
                }
            }else{
                dto.setWeightType("00");
            }

        }


        int diffrentTypeCount = preMuIndexWeightMainMapper.selectDiffrentTypeCount(dto);
        if(diffrentTypeCount > 0){
            String companyType = preMuIndexWeightMain.getCompanyType();
            if(StringUtils.equals("1",companyType)){
                companyType = "规上企业";
            }else{
                companyType = "规下企业";
            }
            throw new RuntimeException("权重方案仅可保留一种，如需新增请先删除现有设置。");
        }

        if (!Arrays.isNullOrEmpty(industryArray)) {
            for(String industry : industryArray){
                params.setIndustry(industry);
                List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainList(params);
                if(preMuIndexWeightMains != null && !preMuIndexWeightMains.isEmpty()){
                    String year = preMuIndexWeightMain.getYear();
                    String companyType = preMuIndexWeightMain.getCompanyType();
                    if(StringUtils.equals("1",companyType)){
                        companyType = "规上企业";
                    }else{
                        companyType = "规下企业";
                    }
                    throw new RuntimeException(String.format("当前年份%s中已添加了%s以及%s行业了,不能重复添加",year,companyType,industry));
                }
            }
        }
        params.setIndustry(null);
        if (!Arrays.isNullOrEmpty(parkArray)) {
            for(String park : parkArray){
                params.setPark(park);
                List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainList(params);
                if(preMuIndexWeightMains != null && !preMuIndexWeightMains.isEmpty()){
                    String year = preMuIndexWeightMain.getYear();
                    String companyType = preMuIndexWeightMain.getCompanyType();
                    if(StringUtils.equals("1",companyType)){
                        companyType = "规上企业";
                    }else{
                        companyType = "规下企业";
                    }
                    throw new RuntimeException(String.format("当前年份%s中已添加了%s以及%s园区了,不能重复添加",year,companyType,park));
                }
            }
        }

        if(Arrays.isNullOrEmpty(industryArray) && Arrays.isNullOrEmpty(parkArray)){
            List<PreMuIndexWeightMain> preMuIndexWeightMains1 = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainList(params);
            if(preMuIndexWeightMains1 != null && !preMuIndexWeightMains1.isEmpty()){
                String year = preMuIndexWeightMain.getYear();
                String companyType = preMuIndexWeightMain.getCompanyType();
                if(StringUtils.equals("1",companyType)){
                    companyType = "规上企业";
                }else{
                    companyType = "规下企业";
                }
                throw new RuntimeException(String.format("当前年份%s中已添加了%s了,不能重复添加",year,companyType));
            }
        }

//        if(!Arrays.isNullOrEmpty(industryArray) && !Arrays.isNullOrEmpty(parkArray)){
//            for(String industry : industryArray){
//                for(String park : parkArray){
//                    params.setIndustry(industry);
//                    params.setPark(park);
//                    List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainList(params);
//                    if(preMuIndexWeightMains != null && !preMuIndexWeightMains.isEmpty()){
//                        String year = preMuIndexWeightMain.getYear();
//                        String companyType = preMuIndexWeightMain.getCompanyType();
//                        if(StringUtils.equals("1",companyType)){
//                            companyType = "规上企业";
//                        }else{
//                            companyType = "规下企业";
//                        }
//                        throw new RuntimeException(String.format("当前年份%s中已添加了%s和%s行业以及%s园区了,不能重复添加",year,companyType,industry,park));
//                    }
//                }
//            }
//        } else if (!Arrays.isNullOrEmpty(industryArray)) {
//            for(String industry : industryArray){
//                params.setIndustry(industry);
//                List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainList(params);
//                if(preMuIndexWeightMains != null && !preMuIndexWeightMains.isEmpty()){
//                    String year = preMuIndexWeightMain.getYear();
//                    String companyType = preMuIndexWeightMain.getCompanyType();
//                    if(StringUtils.equals("1",companyType)){
//                        companyType = "规上企业";
//                    }else{
//                        companyType = "规下企业";
//                    }
//                    throw new RuntimeException(String.format("当前年份%s中已添加了%s以及%s行业了,不能重复添加",year,companyType,industry));
//                }
//            }
//        } else if (!Arrays.isNullOrEmpty(parkArray)) {
//            for(String park : parkArray){
//                params.setPark(park);
//                List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainList(params);
//                if(preMuIndexWeightMains != null && !preMuIndexWeightMains.isEmpty()){
//                    String year = preMuIndexWeightMain.getYear();
//                    String companyType = preMuIndexWeightMain.getCompanyType();
//                    if(StringUtils.equals("1",companyType)){
//                        companyType = "规上企业";
//                    }else{
//                        companyType = "规下企业";
//                    }
//                    throw new RuntimeException(String.format("当前年份%s中已添加了%s以及%s园区了,不能重复添加",year,companyType,park));
//                }
//            }
//        }else{
//            List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainList(params);
//            if(preMuIndexWeightMains != null && !preMuIndexWeightMains.isEmpty()){
//                String year = preMuIndexWeightMain.getYear();
//                String companyType = preMuIndexWeightMain.getCompanyType();
//                if(StringUtils.equals("1",companyType)){
//                    companyType = "规上企业";
//                }else{
//                    companyType = "规下企业";
//                }
//                throw new RuntimeException(String.format("当前年份%s中已添加了%s了,不能重复添加",year,companyType));
//            }
//        }


        preMuIndexWeightMain.setBaseId(IdUtil.simpleUUID());
        BigDecimal resulrtBigDecimal = new BigDecimal("0.00");
        for(PreMuIndexWeightSub item : preMuIndexWeightSubList){
            item.setBaseId(IdUtil.simpleUUID());
            item.setBaseCreateTime(DateUtils.getNowDate());
            item.setBaseCreateBy(SecurityUtils.getUserId());
            item.setPkId(preMuIndexWeightMain.getBaseId());


            BigDecimal indexValueBigDecimal = StringUtils.isBlank(item.getIndexValue()) ? BigDecimal.ZERO : new BigDecimal(item.getIndexValue());
            BigDecimal indexValueLineBigDecimal = StringUtils.isBlank(item.getIndexValueLine()) ? BigDecimal.ZERO : new BigDecimal(item.getIndexValueLine());

            if(indexValueBigDecimal.compareTo(BigDecimal.ZERO)  < 0 || indexValueLineBigDecimal.compareTo(BigDecimal.ZERO) < 0){
                return AjaxResult.error("基准值或权重不可小于0");
            }


            //计算是否大于100
            String indexValue = item.getIndexValue();

            if(StringUtils.isBlank(indexValue)){
                throw new RuntimeException("权重不可为空");
            }
            if(StringUtils.equals(item.getFlType(),"1") && StringUtils.isBlank(item.getIndexValueLine())){
                throw new RuntimeException("基准值不可为空");
            }
            resulrtBigDecimal = resulrtBigDecimal.add(new BigDecimal(StringUtils.isBlank(indexValue) ? "0.00" : indexValue));

        }

        if(resulrtBigDecimal.doubleValue() > 100.00){
            throw new RuntimeException("设置的指标值不能大于100");
        }

        BigDecimal sjScore = preMuIndexWeightSubList.stream().filter(k -> StringUtils.equals(k.getFlType(), "1")).map(k -> new BigDecimal(StringUtils.isBlank(k.getIndexValue()) ? "0.00" : k.getIndexValue())).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        if(sjScore.compareTo(BigDecimal.valueOf(70L)) < 0){
            throw new RuntimeException("省级设定指标不能小于70分");
        }

        //区县特色指标分数
        BigDecimal qxScore = preMuIndexWeightSubList.stream().filter(k -> StringUtils.equals(k.getFlType(), "2")).map(k -> new BigDecimal(StringUtils.isBlank(k.getIndexValue()) ? "0.00" : k.getIndexValue())).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        if(qxScore.compareTo(BigDecimal.valueOf(30L)) > 0){
            throw new RuntimeException("区县特色指标不能大于30分");
        }

        preMuIndexWeightMain.setCounty(district);
        preMuIndexWeightMain.setBaseCreateTime(DateUtils.getNowDate());
        preMuIndexWeightMain.setBaseCreateBy(SecurityUtils.getUserId());
        preMuIndexWeightMainMapper.insertPreMuIndexWeightMain(preMuIndexWeightMain);
        preMuIndexWeightSubMapper.batchInsertPreMuIndexValue(preMuIndexWeightSubList);


        return AjaxResult.success("保存成功");
    }

    @Autowired
    private PreMuBenefitEvaluationMapper preMuBenefitEvaluationMapper;

    /**
     * 修改指标管理主
     *
     * @param preMuIndexWeightMain 指标管理主
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updatePreMuIndexWeightMain(PreMuIndexWeightMain preMuIndexWeightMain)
    {
        String district = SecurityUtils.getLoginUser().getSysUser().getDistrict();
        PreMuIndexWeightMain queryParams = new PreMuIndexWeightMain();
        queryParams.setYear(preMuIndexWeightMain.getYear());
        queryParams.setCounty(district);
        queryParams.setCompanyType(preMuIndexWeightMain.getCompanyType());
        Integer importDataCount = preMuImportCustomIndexLjMapper.selectCurrentCountyYearCompanyTypeImportDataList(queryParams);
        if(importDataCount > 0){
            return AjaxResult.warn("当前指标已在涉企数据中导入数据，无法修改");
        }

        String industries = preMuIndexWeightMain.getIndustry();
        String parks = preMuIndexWeightMain.getPark();
        String[] industryArray = new String[]{};
        String[] parkArray = new String[]{};
        if(!StringUtils.isEmpty(industries)){
            industryArray = industries.split(",");

        }
        if(!StringUtils.isEmpty(parks)){
            parkArray = parks.split(",");

        }
        queryParams.setBaseId(preMuIndexWeightMain.getBaseId());

        PreMuIndexWeightMainDto dto = new PreMuIndexWeightMainDto();
        dto.setCounty(district);
        dto.setYear(preMuIndexWeightMain.getYear());
        dto.setCompanyType(preMuIndexWeightMain.getCompanyType());
        dto.setBaseId(preMuIndexWeightMain.getBaseId());
        if(!Arrays.isNullOrEmpty(industryArray) && !Arrays.isNullOrEmpty(parkArray)){
            dto.setWeightType("03");
        }else{
            if(!Arrays.isNullOrEmpty(industryArray) || !Arrays.isNullOrEmpty(parkArray)){
                if(Arrays.isNullOrEmpty(industryArray)){
                    dto.setWeightType("02");
                }else if(Arrays.isNullOrEmpty(parkArray)){
                    dto.setWeightType("01");
                }
            }else{
                dto.setWeightType("00");
            }

        }
        int diffrentTypeCount = preMuIndexWeightMainMapper.selectDiffrentTypeCount(dto);
        if(diffrentTypeCount > 0){
            String companyType = preMuIndexWeightMain.getCompanyType();
            if(StringUtils.equals("1",companyType)){
                companyType = "规上企业";
            }else{
                companyType = "规下企业";
            }
            throw new RuntimeException("权重方案仅可保留一种，如需新增请先删除现有设置。");
        }


        if (!Arrays.isNullOrEmpty(industryArray)) {
            for(String industry : industryArray){
                queryParams.setIndustry(industry);
                int existCount = preMuIndexWeightMainMapper.selectWeightMainExistCount(queryParams);
                if(existCount > 0){
                    String year = preMuIndexWeightMain.getYear();
                    String companyType = preMuIndexWeightMain.getCompanyType();
                    if(StringUtils.equals("1",companyType)){
                        companyType = "规上企业";
                    }else{
                        companyType = "规下企业";
                    }
                    throw new RuntimeException(String.format("当前年份%s中已添加了%s以及%s行业了,不能重复添加",year,companyType,industry));
                }
            }
        }
        queryParams.setIndustry(null);
        if (!Arrays.isNullOrEmpty(parkArray)) {
            for(String park : parkArray){
                queryParams.setPark(park);
                int existCount = preMuIndexWeightMainMapper.selectWeightMainExistCount(queryParams);
                if(existCount > 0){
                    String year = preMuIndexWeightMain.getYear();
                    String companyType = preMuIndexWeightMain.getCompanyType();
                    if(StringUtils.equals("1",companyType)){
                        companyType = "规上企业";
                    }else{
                        companyType = "规下企业";
                    }
                    throw new RuntimeException(String.format("当前年份%s中已添加了%s以及%s园区了,不能重复添加",year,companyType,park));
                }
            }
        }
        if(Arrays.isNullOrEmpty(industryArray) && Arrays.isNullOrEmpty(parkArray)){
            int existCount1 = preMuIndexWeightMainMapper.selectWeightMainExistCount(queryParams);
            if(existCount1 > 0){
                String year = preMuIndexWeightMain.getYear();
                String companyType = preMuIndexWeightMain.getCompanyType();
                if(StringUtils.equals("1",companyType)){
                    companyType = "规上企业";
                }else{
                    companyType = "规下企业";
                }
                throw new RuntimeException(String.format("当前年份%s中已添加了%s了,不能重复添加",year,companyType));
            }
        }
//        if(!Arrays.isNullOrEmpty(industryArray) && !Arrays.isNullOrEmpty(parkArray)){
//            for(String industry : industryArray){
//                for(String park : parkArray){
//                    queryParams.setIndustry(industry);
//                    queryParams.setPark(park);
//                    queryParams.setBaseId(preMuIndexWeightMain.getBaseId());
//                    int existCount = preMuIndexWeightMainMapper.selectWeightMainExistCount(queryParams);
//                    if(existCount > 0){
//                        String year = preMuIndexWeightMain.getYear();
//                        String companyType = preMuIndexWeightMain.getCompanyType();
//                        if(StringUtils.equals("1",companyType)){
//                            companyType = "规上企业";
//                        }else{
//                            companyType = "规下企业";
//                        }
//                        throw new RuntimeException(String.format("当前年份%s中已添加了%s和%s行业以及%s园区了,不能重复添加",year,companyType,industry,park));
//                    }
//                }
//            }
//        } else if (!Arrays.isNullOrEmpty(industryArray)) {
//            for(String industry : industryArray){
//                queryParams.setIndustry(industry);
//                int existCount = preMuIndexWeightMainMapper.selectWeightMainExistCount(queryParams);
//                if(existCount > 0){
//                    String year = preMuIndexWeightMain.getYear();
//                    String companyType = preMuIndexWeightMain.getCompanyType();
//                    if(StringUtils.equals("1",companyType)){
//                        companyType = "规上企业";
//                    }else{
//                        companyType = "规下企业";
//                    }
//                    throw new RuntimeException(String.format("当前年份%s中已添加了%s以及%s行业了,不能重复添加",year,companyType,industry));
//                }
//            }
//        } else if (!Arrays.isNullOrEmpty(parkArray)) {
//            for(String park : parkArray){
//                queryParams.setPark(park);
//                int existCount = preMuIndexWeightMainMapper.selectWeightMainExistCount(queryParams);
//                if(existCount > 0){
//                    String year = preMuIndexWeightMain.getYear();
//                    String companyType = preMuIndexWeightMain.getCompanyType();
//                    if(StringUtils.equals("1",companyType)){
//                        companyType = "规上企业";
//                    }else{
//                        companyType = "规下企业";
//                    }
//                    throw new RuntimeException(String.format("当前年份%s中已添加了%s以及%s园区了,不能重复添加",year,companyType,park));
//                }
//            }
//        }else{
//            int existCount = preMuIndexWeightMainMapper.selectWeightMainExistCount(queryParams);
//            if(existCount > 0){
//                String year = preMuIndexWeightMain.getYear();
//                String companyType = preMuIndexWeightMain.getCompanyType();
//                if(StringUtils.equals("1",companyType)){
//                    companyType = "规上企业";
//                }else{
//                    companyType = "规下企业";
//                }
//                throw new RuntimeException(String.format("当前年份%s中已添加了%s了,不能重复添加",year,companyType));
//            }
//        }
        //查询区县数据是否汇入了
        PreMuBenefitEvaluation preMuBenefitEvaluation = new PreMuBenefitEvaluation();
        preMuBenefitEvaluation.setYears(preMuIndexWeightMain.getYear());
        preMuBenefitEvaluation.setCounty(district);
        preMuBenefitEvaluation.setCompanyType(preMuIndexWeightMain.getCompanyType());
        Integer hrCount = preMuBenefitEvaluationMapper.selectCurrentCountyHrData(preMuBenefitEvaluation);
        if(hrCount > 0){
            return AjaxResult.warn("当前区县的数据已汇入，无法修改指标数据");
        }
        List<PreMuIndexWeightSub> preMuIndexWeightSubList = preMuIndexWeightMain.getPreMuIndexWeightSubList();
        BigDecimal resulrtBigDecimal = new BigDecimal("0.00");
        preMuIndexWeightSubMapper.deletePreMuIndexWeightSubByPkId(preMuIndexWeightMain.getBaseId());
        for(PreMuIndexWeightSub item : preMuIndexWeightSubList){
            item.setBaseId(IdUtil.simpleUUID());
            item.setBaseCreateTime(DateUtils.getNowDate());
            item.setBaseCreateBy(SecurityUtils.getUserId());
            item.setPkId(preMuIndexWeightMain.getBaseId());

            //计算是否大于100
            String indexValue = item.getIndexValue();
            if(StringUtils.isBlank(indexValue)){
                throw new RuntimeException("权重不可为空");
            }
            if(StringUtils.equals(item.getFlType(),"1") && StringUtils.isBlank(item.getIndexValueLine())){
                throw new RuntimeException("基准值不可为空");
            }
            resulrtBigDecimal = resulrtBigDecimal.add(new BigDecimal(StringUtils.isBlank(indexValue) ? "0.00" : indexValue));
        }

        BigDecimal z100 = new BigDecimal("100");
        if(z100.compareTo(resulrtBigDecimal) < 0){
            throw new RuntimeException("设置的指标值不能大于100");
        }

        BigDecimal sjScore = preMuIndexWeightSubList.stream().filter(k -> StringUtils.equals(k.getFlType(), "1")).map(k -> new BigDecimal(StringUtils.isBlank(k.getIndexValue()) ? "0.00" : k.getIndexValue())).reduce(BigDecimal::add).get();
        if(sjScore.compareTo(BigDecimal.valueOf(70L)) < 0){
            throw new RuntimeException("省级设定指标不能小于70分");
        }

        //区县特色指标分数
        BigDecimal qxScore = preMuIndexWeightSubList.stream().filter(k -> StringUtils.equals(k.getFlType(), "2")).map(k -> new BigDecimal(StringUtils.isBlank(k.getIndexValue()) ? "0.00" : k.getIndexValue())).reduce(BigDecimal::add).get();
        if(qxScore.compareTo(BigDecimal.valueOf(30L)) > 0){
            throw new RuntimeException("区县特色指标不能大于30分");
        }

        preMuIndexWeightSubMapper.batchInsertPreMuIndexValue(preMuIndexWeightSubList);
        preMuIndexWeightMainMapper.updatePreMuIndexWeightMain(preMuIndexWeightMain);
        return AjaxResult.success();
    }

    /**
     * 批量删除指标管理主
     *
     * @param baseIds 需要删除的指标管理主主键
     * @return 结果
     */
    @Override
    public int deletePreMuIndexWeightMainByBaseIds(String[] baseIds)
    {
        return preMuIndexWeightMainMapper.deletePreMuIndexWeightMainByBaseIds(baseIds);
    }

    /**
     * 删除指标管理主信息
     *
     * @param baseId 指标管理主主键
     * @return 结果
     */
    @Override
    public int deletePreMuIndexWeightMainByBaseId(String baseId)
    {
        return preMuIndexWeightMainMapper.deletePreMuIndexWeightMainByBaseId(baseId);
    }

    @Override
    public AjaxResult queryIndexValue(PreMuIndexWeightMain preMuIndexWeightMain) {
        PreMuIndexWeightMain dbData = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainByBaseId(preMuIndexWeightMain.getBaseId());
        if(dbData == null){
            return AjaxResult.success();
        }
        PreMuIndexWeightSub pa = new PreMuIndexWeightSub();
        pa.setPkId(preMuIndexWeightMain.getBaseId());
        List<PreMuIndexWeightSub> preMuIndexWeightSubs = preMuIndexWeightSubMapper.selectPreMuIndexWeightSubList(pa);
        dbData.setPreMuIndexWeightSubList(preMuIndexWeightSubs);
        return AjaxResult.success(dbData);
    }

    @Override
    public PreMuIndexWeightMain selectOne(PreMuIndexWeightMain indexWeightParams) {
        PreMuIndexWeightMain p = preMuIndexWeightMainMapper.selectOne(indexWeightParams);
        if(p != null && p.getPreMuIndexWeightSubList() != null){
            List<PreMuIndexWeightSub> preMuIndexWeightSubList = p.getPreMuIndexWeightSubList();
            if(preMuIndexWeightSubList != null && !preMuIndexWeightSubList.isEmpty()){
                List<PreMuIndexWeightSub> collect = preMuIndexWeightSubList.stream().filter(item -> StringUtils.equals(item.getFlType(), "2")).collect(Collectors.toList());
                p.setPreMuIndexWeightSubList(collect);
            }
        }
        return p;
    }

    /**
     * 导出指标管理数据
     *
     * @param preMuIndexWeightMain
     * @return
     */
    @Override
    public Workbook exportIndexManange(PreMuIndexWeightMain preMuIndexWeightMain) {
        Workbook wb = null;
        try{
            wb = new SXSSFWorkbook(500);
            XSSFCellStyle headerStyle = (XSSFCellStyle) wb.createCellStyle();
            headerStyle.setBorderLeft(BorderStyle.THIN);
            headerStyle.setBorderTop(BorderStyle.THIN);
            headerStyle.setBorderRight(BorderStyle.THIN);
            headerStyle.setBorderBottom(BorderStyle.THIN);
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);    //设置填充方案
            headerStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(180,198,231)));  //设置填充颜色

            List<PreMuIndexWeightMain> result = preMuIndexWeightMainMapper.selectSubList(preMuIndexWeightMain);

            if(result != null && !result.isEmpty()){
                //规上的指标
                Map<String, List<PreMuIndexWeightMain>> groupIndexMap = result.stream().collect(Collectors.groupingBy(i -> {
                    String year = i.getYear();
                    String companyType = StringUtils.equals(i.getCompanyType(), "1") ? "规上企业" : "规下企业";
                    return companyType + "-" + year;
                }));
                for(Map.Entry<String, List<PreMuIndexWeightMain>> i : groupIndexMap.entrySet()){
                    String key = i.getKey();
                    List<PreMuIndexWeightMain> mainIndexList = i.getValue();

                    SXSSFSheet sheet = ((SXSSFWorkbook) wb).createSheet(key);
                    SXSSFRow row = sheet.createRow(0);
                    SXSSFCell usccNameCell = row.createCell(0, CellType.STRING);
                    usccNameCell.setCellStyle(headerStyle);
                    usccNameCell.setCellValue("企类类型");
                    SXSSFCell companyNameCell = row.createCell(1, CellType.STRING);
                    companyNameCell.setCellStyle(headerStyle);
                    companyNameCell.setCellValue("区县名称");
                    SXSSFCell yearNameCell = row.createCell(2, CellType.STRING);
                    yearNameCell.setCellStyle(headerStyle);
                    yearNameCell.setCellValue("年度");
                    SXSSFCell industryNameCell = row.createCell(3, CellType.STRING);
                    industryNameCell.setCellStyle(headerStyle);
                    industryNameCell.setCellValue("行业");
                    SXSSFCell parkNameCell = row.createCell(4, CellType.STRING);
                    parkNameCell.setCellStyle(headerStyle);
                    parkNameCell.setCellValue("园区");

                    //填充其他的标头
                    for(PreMuIndexWeightMain mainIndex : mainIndexList){
                        List<PreMuIndexWeightSub> preMuIndexWeightSubList = mainIndex.getPreMuIndexWeightSubList();
                        for(int index = 0;index < preMuIndexWeightSubList.size();index++){
                            PreMuIndexWeightSub preMuIndexWeightSub = preMuIndexWeightSubList.get(index);
                            if(preMuIndexWeightSub != null){
                                String indexName = preMuIndexWeightSub.getIndexName();
                                SXSSFCell indexNameCell = row.createCell(index + 5 + index, CellType.STRING);
                                SXSSFCell indexNameBaseLineCell = row.createCell(index + 6 + index, CellType.STRING);
                                indexNameCell.setCellStyle(headerStyle);
                                indexNameCell.setCellValue(indexName);
                                indexNameBaseLineCell.setCellStyle(headerStyle);
                                indexNameBaseLineCell.setCellValue(indexName + "(基准值)" );
                            }
                        }
                    }

                    //填充数据
                    for(int dataIndex = 0;dataIndex < mainIndexList.size();dataIndex++){
                        PreMuIndexWeightMain dataMain = mainIndexList.get(dataIndex);
                        String year = dataMain.getYear();
                        String companyType = StringUtils.equals(dataMain.getCompanyType(),"1") ? "规上企业" : "规下企业";
                        String county = redisTemplate.opsForValue().get("area:" + preMuIndexWeightMain.getCounty());
                        //创建当前行
                        SXSSFRow currentRow = sheet.createRow(dataIndex + 1);
                        SXSSFRow zeroRow = sheet.getRow(0);

                        SXSSFCell ctCell = currentRow.createCell(0);
                        ctCell.setCellValue(companyType);
                        SXSSFCell countyCell = currentRow.createCell(1);
                        countyCell.setCellValue(county);
                        SXSSFCell yearCell = currentRow.createCell(2);
                        yearCell.setCellValue(year);
                        SXSSFCell industryCell = currentRow.createCell(3);
                        industryCell.setCellValue(dataMain.getIndustryName());
                        SXSSFCell parkCell = currentRow.createCell(4);
                        parkCell.setCellValue(dataMain.getPark());
                        List<PreMuIndexWeightSub> preMuIndexWeightSubList = dataMain.getPreMuIndexWeightSubList();
                        for(int index = 0;index < preMuIndexWeightSubList.size();index++){
                            PreMuIndexWeightSub preMuIndexWeightSub = preMuIndexWeightSubList.get(index);
                            SXSSFCell currentRowCell = currentRow.createCell(index + 5 +index);
                            SXSSFCell currentRowJzCell = currentRow.createCell(index + 6 + index);

                            if(StringUtils.isBlank(preMuIndexWeightSub.getIndexValue())){
                                currentRowCell.setCellValue("");
                            }else{
                                currentRowCell.setCellValue(preMuIndexWeightSub.getIndexValue());
                            }
                            if(StringUtils.isBlank(preMuIndexWeightSub.getIndexValueLine())){
                                currentRowJzCell.setCellValue("");
                            }else{
                                currentRowJzCell.setCellValue(preMuIndexWeightSub.getIndexValueLine());
                            }

                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return wb;
    }

    @Autowired
    private PreMuIndexWeightMapper preMuIndexWeightMapper;

    /**
     * <p>
     * 新增指标管理
     * </p>
     *
     * @param preMuIndexWeight
     * @return
     */
    @Override
    public void addIndexManager(PreMuIndexWeight preMuIndexWeight) {
        preMuIndexWeight.setId(IdUtil.simpleUUID());
        preMuIndexWeightMapper.addIndexManager(preMuIndexWeight);
    }

    @Override
    public PreMuIndexWeightMainVo selecPreMuIndexWeightMain(IndexWeightParamsDto indexWeightParams) {
        return preMuIndexWeightMainMapper.selecPreMuIndexWeightMain(indexWeightParams);
    }

    @Override
    public List<PreMuIndexWeightMainVo> weightList(IndexWeightParamsDto indexWeightParams) {
        return preMuIndexWeightMainMapper.weightList(indexWeightParams);
    }

    @Override
    public int weightCount(IndexWeightParamsDto indexWeightParams) {
        return preMuIndexWeightMainMapper.weightCount(indexWeightParams);
    }
}
